MODULE_NAME='Debug Log'
(
	Dev vdvConnection,
	Dev vdvInterface,
	Char strClientName[],
	Char strDestinationEmail[]
)
(***********************************************************)
(***********************************************************)
(*  FILE_LAST_MODIFIED_ON: 04/04/2006  AT: 11:33:16        *)
(***********************************************************)
(* System Type : NetLinx                                   *)
(***********************************************************)
(* REV HISTORY:                                            *)
(***********************************************************)
(*
    $History: $
*)    
//#Define DEBUG = 1 // careful having this active since it
                  // could cause a infinite loop
(***********************************************************)
(*          DEVICE NUMBER DEFINITIONS GO BELOW             *)
(***********************************************************)
DEFINE_DEVICE

(***********************************************************)
(*               CONSTANT DEFINITIONS GO BELOW             *)
(***********************************************************)
DEFINE_CONSTANT
cnTimelineID = 33
Long cnTimelineTimes[] = {10000}

cnTimelineQty = 1

cnMaxFileSize = 1000000
cnMaxBufferSize = 2000
cnMaxDailyEmailQty = 4

(***********************************************************)
(*              DATA TYPE DEFINITIONS GO BELOW             *)
(***********************************************************)
DEFINE_TYPE

(***********************************************************)
(*               VARIABLE DEFINITIONS GO BELOW             *)
(***********************************************************)
DEFINE_VARIABLE
Volatile SInteger nResult
Volatile SInteger nFileHandle
Volatile SLong nFilePos
Volatile SInteger nFileResult
Non_Volatile Integer nDailyEmailQty
Non_Volatile Char strOldDate[100]

Volatile Char strFilePath[] = 'Log.txt'
Volatile Char strTempFilePath[] = 'EmailLog.txt'
Volatile Char strDebugData[cnMaxBufferSize]
Volatile Char strData[cnMaxBufferSize]

Volatile IP_ADDRESS_STRUCT sMyIPAddress (* .Flags *)
(* .HostName *)
(* .IPAddress *)
(* .SubnetMask *)
(* .Gateway *)
#IF_DEFINED DEBUG
Integer nI
Integer nFillTheBufferPlease
#END_IF

(***********************************************************)
(*               LATCHING DEFINITIONS GO BELOW             *)
(***********************************************************)
DEFINE_LATCHING

(***********************************************************)
(*       MUTUALLY EXCLUSIVE DEFINITIONS GO BELOW           *)
(***********************************************************)
DEFINE_MUTUALLY_EXCLUSIVE

(***********************************************************)
(*        SUBROUTINE/FUNCTION DEFINITIONS GO BELOW         *)
(***********************************************************)
(* EXAMPLE: DEFINE_FUNCTION <RETURN_TYPE> <NAME> (<PARAMETERS>) *)
(* EXAMPLE: DEFINE_CALL '<NAME>' (<PARAMETERS>) *)
#Include 'i!-EquipmentMonitorOut.axi'

Define_Call 'DEBUG_OUTPUT' (Integer nLine, Char strData[])
{
	#IF_DEFINED DEBUG
	Send_String 0,"__FILE__,' Line:',Itoa(nLine),' ',strData"
	#END_IF
}

DEFINE_FUNCTION CHAR[100] GET_IP_ERROR (LONG lERR)
{
  SELECT
  {
    ACTIVE (lERR = 0):
      RETURN "";
    ACTIVE (lERR = 2):
      RETURN "'IP ERROR (',ITOA(lERR),'): General Failure (IP_CLIENT_OPEN/IP_SERVER_OPEN)'";
    ACTIVE (lERR = 4):
      RETURN "'IP ERROR (',ITOA(lERR),'): unknown host (IP_CLIENT_OPEN)'";
    ACTIVE (lERR = 6):
      RETURN "'IP ERROR (',ITOA(lERR),'): connection refused (IP_CLIENT_OPEN)'";
    ACTIVE (lERR = 7):
      RETURN "'IP ERROR (',ITOA(lERR),'): connection timed out (IP_CLIENT_OPEN)'";
    ACTIVE (lERR = 8):
      RETURN "'IP ERROR (',ITOA(lERR),'): unknown connection error (IP_CLIENT_OPEN)'";
    ACTIVE (lERR = 14):
      RETURN "'IP ERROR (',ITOA(lERR),'): local port already used (IP_CLIENT_OPEN/IP_SERVER_OPEN)'";
    ACTIVE (lERR = 16):
      RETURN "'IP ERROR (',ITOA(lERR),'): too many open sockets (IP_CLIENT_OPEN/IP_SERVER_OPEN)'";
    ACTIVE (lERR = 10):
      RETURN "'IP ERROR (',ITOA(lERR),'): Binding error (IP_SERVER_OPEN)'";
    ACTIVE (lERR = 11):
      RETURN "'IP ERROR (',ITOA(lERR),'): Listening error (IP_SERVER_OPEN)'";
    ACTIVE (lERR = 15):
      RETURN "'IP ERROR (',ITOA(lERR),'): UDP socket already listening (IP_SERVER_OPEN)'";
    ACTIVE (lERR = 9):
      RETURN "'IP ERROR (',ITOA(lERR),'): Already closed (IP_CLIENT_CLOSE/IP_SERVER_CLOSE)'";
    ACTIVE (1):
      RETURN "'IP ERROR (',ITOA(lERR),'): Unknown'";
  }
}

(***********************************************************)
(*                STARTUP CODE GOES BELOW                  *)
(***********************************************************)
DEFINE_START
SmtpSetServer('mail.paragonintranet.com')
SmtpSetUser('crestron+paragonintranet.com','Cr3str0n123')
//SmtpSetServer('mail.sopris.net')
//SmtpSetUser('russellmelton@sopris.net','killer')

Wait 100
{
	Get_Ip_Address(0:0:0,sMyIPAddress) // Populates the struct sMyIPAddress
	nResult = 1 // This needs to be a non zero number since 0 is a good conenction
	Timeline_Create(cnTimelineID, cnTimelineTimes, cnTimelineQty, Timeline_Relative, Timeline_Repeat) // start trying to connect
}

(***********************************************************)
(*                THE EVENTS GO BELOW                      *)
(***********************************************************)
DEFINE_EVENT

Timeline_Event[cnTimelineID]
{
	nResult = Ip_Client_Open(vdvConnection.Port, sMyIPAddress.IPAddress, 23, 1) // Connect to the local master
}

Data_Event[vdvConnection]
{
	OnError:
	{
    If (Data.Number != 14)
      nResult = 1  // set connection state to a invalid number (0 = connected)
    Call 'DEBUG_OUTPUT' (__LINE__,"GET_IP_ERROR (Data.Number)")
	}
	Online:
	{
		Timeline_Kill(cnTimelineID) // stop trying to reconnect
		Send_String vdvConnection,"'msg on',13"
		#IF_DEFINED DEBUG
		nFillTheBufferPlease = 1
		#END_IF
	}
	Offline:
	{
		Timeline_Create(cnTimelineID, cnTimelineTimes, cnTimelineQty, Timeline_Relative, Timeline_Repeat) // try to reconnect
		#IF_DEFINED DEBUG
		nFillTheBufferPlease = 0
		#END_IF
	}
	String:
	{
		Integer nDebugLen, nDataLen
		strData = "DATE,' ',TIME,':',Data.Text"
		nDebugLen = Length_String(strDebugData)
		nDataLen = Length_String(strData)
		If (nDebugLen + nDataLen < cnMaxBufferSize)
		{
			strDebugData = "strDebugData,DATE,' ',TIME,':',Data.Text"
		}
		Else
		{
			Call 'DEBUG_OUTPUT' (__LINE__,"'Writing strDebugData(',Itoa(nDebugLen),') to file.  Len(',Itoa(nDataLen),')'")
			nFileHandle = File_Open(strFilePath,3) // Open and append new information
			If (nFileHandle <= 0) // file open failed.  file migfht not exist
			{
				File_Open(strFilePath,2) // Create and open new file
				Call 'DEBUG_OUTPUT' (__LINE__,"'Could not find existing debug file so creating a new one.'")
			}
			nFilePos = File_Seek(nFileHandle,cnMaxFileSize) // < 0 means files isnt that big.  > 0 means it is larger than cnMaxFileSize
			Call 'DEBUG_OUTPUT' (__LINE__,"'File seek:',Itoa(nFilePos)")
			If (nFilePos >= 0) // File must be greater cnMaxFileSize
			{
				File_Close(nFileHandle) // close the full file
				nFileResult = File_Copy(strFilePath,strTempFilePath)
				If (nFileResult == 0) // copy was succesful
				{
					//Send Email
					nDailyEmailQty++
					If (strOldDate != Date)
					{
						Call 'DEBUG_OUTPUT' (__LINE__,"'Cleared nDailyEmailQty. ',strOldDate,' != ',Date")
						strOldDate = Date
						nDailyEmailQty = 1
					}
					
					If (nDailyEmailQty <= cnMaxDailyEmailQty)
					{
						Call 'DEBUG_OUTPUT' (__LINE__,'Emailing new file.')
						SmtpQueMessage('crestron@paragon-usa.com', // source
												"strDestinationEmail", // destination
												"strClientName,' Report'", // subject
												"'Sent:',Date,' ',Time", // msg text
												strTempFilePath) // file
					}
					Else
					{
						Call 'DEBUG_OUTPUT' (__LINE__,"'Not Emailing new file due to nDailyEmailQty(',Itoa(nDailyEmailQty),') > cnMaxDailyEmailQty(',Itoa(cnMaxDailyEmailQty),').'")
					}
				}
				Else
				{
					Call 'DEBUG_OUTPUT' (__LINE__,"'Failed to copy file:',Itoa(nFileResult)")
				}
				nFileHandle = File_Open(strFilePath,2) // This will clear the old file
			}
			nFileResult = File_Write(nFileHandle,strDebugData,Length_String(strDebugData))
			Call 'DEBUG_OUTPUT' (__LINE__,"'File write line:',Itoa(nFileResult)")
			File_Close(nFileHandle)
			strDebugData = "DATE,' ',TIME,':',Data.Text" // make up the line that would have put us over the limit and leave it for next time
		}
	}
}

Button_Event[vdvInterface,1]
{
	Push:
	{
		Call 'DEBUG_OUTPUT' (__LINE__,'Manually emailing current file.')
		SmtpQueMessage('crestron@paragonintranet.com', // source
								"strDestinationEmail", // destination
								"strClientName,' Report'", // subject
								"'Manually Sent:',Date,' ',Time", // msg text
								strFilePath) // file		
	}
}

Button_Event[vdvInterface,2]
{
	Push:
	{
		Call 'DEBUG_OUTPUT' (__LINE__,'Manually emailing temp file.')
		SmtpQueMessage('crestron@paragonintranet.com', // source
								"strDestinationEmail", // destination
								"strClientName,' Report'", // subject
								"'Temp Manually Sent:',Date,' ',Time", // msg text
								strTempFilePath) // file		
	}
}

(***********************************************************)
(*            THE ACTUAL PROGRAM GOES BELOW                *)
(***********************************************************)
DEFINE_PROGRAM
/*#IF_DEFINED DEBUG
Wait 4
{
	If (nFillTheBufferPlease && nI < 5000)
	{
		nI++
		Send_String 0,"'This is test #',Itoa(nI),'.  If this were real there would be useless data attached.'"
	}
}
#END_IF */

(***********************************************************)
(*                     END OF PROGRAM                      *)
(*        DO NOT PUT ANY CODE BELOW THIS COMMENT           *)
(***********************************************************)
